package com.hoshiicloud.shxping.jobhandler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.DateUtil;
import com.hoshiicloud.saleorder.dto.OrderDTO;
import com.hoshiicloud.saleorder.param.OrderMainIdsUpdateParam;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.param.OrderQueryParam;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yangcheng
 * @version 1.0
 * @title: AutoVerificationOrderHandler
 * @description: 自动核销订单任务
 * @date 2019/9/1 18:11
 * @mail maiboyc@163.com
 */
@JobHandler("autoVerificationOrderHandler")
@Component
public class AutoVerificationOrderHandler extends IJobHandler {

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public ReturnT<String> execute(String s) {
        try {
            XxlJobLogger.log("自动核销订单任务begin----", System.currentTimeMillis());

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //查询待提货订单
            OrderQueryParam param = new OrderQueryParam();
            param.setStatus(3);
            Response<List<OrderDTO>> response = orderFeignService.listAllOrders(param);

            if (response != null && response.getData() != null && response.getData().size() > 0) {

                //主订单id
                List<Long> orderIds = new ArrayList<>();
                for (OrderDTO orderDTO : response.getData()) {
                    System.out.println(JSON.toJSONString(orderDTO));
                    //已过提货天数
                    int day = DateUtil.differentDaysByMillisecond(format.parse(orderDTO.getDeliveryTime()), new Date());

                    if (day > 3) {
                        orderIds.add(orderDTO.getOrderId());
                    }
                }
                if (orderIds.size() > 0) {
                    //批量核销
                    OrderMainIdsUpdateParam orderIdsParam = OrderMainIdsUpdateParam.builder().orderIds(orderIds).build();
                    orderFeignService.verificationBatchOrder(orderIdsParam);
                }

            }

            XxlJobLogger.log("自动核销订单任务end----");

        } catch (Exception e) {
            XxlJobLogger.log("订单核销任务异常：", e);
        }
        return SUCCESS;
    }
}
